# -*- coding: utf-8 -*-
"""
认证工具函数
"""
from functools import wraps
from flask import request, g
from app.services.auth_service import AuthService
from app.config.database import SessionLocal
from app.utils.response import unauthorized_response, token_invalid_response

def token_required(f):
    """
    需要令牌验证的装饰器
    """
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None

        # 从请求头获取令牌
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            try:
                token = auth_header.split(" ")[1]  # Bearer <token>
            except IndexError:
                return unauthorized_response("令牌格式错误")

        if not token:
            return unauthorized_response("缺少访问令牌")

        try:
            # 验证令牌
            db = SessionLocal()
            current_user = AuthService.get_current_user(db, token)
            db.close()

            if not current_user:
                return token_invalid_response("令牌无效或已过期")

            g.current_user = current_user

        except Exception as e:
            return token_invalid_response("令牌验证失败")

        return f(*args, **kwargs)

    return decorated

def get_current_user():
    """
    获取当前登录用户
    """
    return getattr(g, 'current_user', None)